package com.heba.greenmulu.scan;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.product.ItemProductDetailObject;
import com.heba.dialog.CustomDialogView;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.ToastShow;
import com.heba.utils.UniversalImageLoadTool;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户收藏产品编辑
 * Created by jason on 2019/3/13.
 */

public class ItemSavedEditActivity extends BaseActivity {

    private TextView txt_right;
    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private List<ItemProductDetailObject> productObjects = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_product_saved_edit);
        initTopbar();
        findViewById();
        initView();
        getProductData();
    }

    @Override
    protected void findViewById() {
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
        txt_right = findViewById(R.id.txt_right);
    }

    @Override
    protected void initView() {
        txt_title.setText(getResources().getString(R.string.barcode_scan));
        txt_right.setText(getResources().getString(R.string.confirm));
        img_back.setVisibility(View.INVISIBLE);
        txt_right.setOnClickListener(v -> finish());

        recycleAdapter = new QuickAdapter<ItemProductDetailObject>(productObjects) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_scan_product;
            }

            @Override
            public void convert(VH holder, final ItemProductDetailObject data, int position) {
                UniversalImageLoadTool.disPlay(data.getIcon(), holder.getView(R.id.img_photo), R.drawable.btn_upload_image);
                holder.setText(R.id.txt_product, data.getBrandName());
                holder.setText(R.id.txt_content, data.getProductName());
                ImageView img_delete = holder.getView(R.id.img_delete);
                img_delete.setVisibility(View.VISIBLE);
                img_delete.setOnClickListener(v -> new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                    @Override
                    public void onYesClick() {
                        //删除收藏产品
//                        progressDialog.show();
                        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                            @Override
                            public void Success() {
//                                progressDialog.dismiss();
                                productObjects.remove(position);
                                notifyItemRemoved(position);
                                notifyItemRangeChanged(position, productObjects.size() - position);
                            }

                            @Override
                            public void Fail(String error) {
//                                progressDialog.dismiss();
                            }
                        }).uncollectProduct(ItemSavedEditActivity.this, data.getProductID());
                    }

                    @Override
                    public void onNoClick() {

                    }
                }).showDialog(ItemSavedEditActivity.this, getResources().getString(R.string.confirm_delete), ""));
            }
        };

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
        //设置分隔线
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
        //设置增加或删除条目的动画
//        recyclerView.setItemAnimator(new DefaultItemAnimator());

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
                getProductData();
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
                getProductData();
            }
        });
    }

    /**
     * 获取收藏产品
     */
    private void getProductData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", PerPage);
        client.get(Cfg.BaseUrl + "/Product/Saved", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();

                        /**
                         * 判断是否需要清除数据
                         */
                        if (isRefreshFromTop) {
                            if (!productObjects.isEmpty()) {
                                productObjects.clear();
                            }
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }

                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateProductData(array);
                            } else {
                                recycleAdapter.notifyDataSetChanged();
                                ToastShow.displayToast(ItemSavedEditActivity.this, getResources().getString(R.string.finish_no_data));
                                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        if (isRefreshFromTop) {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishRefresh();
                                refreshLayout.setNoMoreData(false);
                            }
                        } else {
                            if (refreshLayout.getState().isOpening) {
                                refreshLayout.finishLoadMore();
                                refreshLayout.setNoMoreData(false);
                            }
                        }
                    }

                });
    }

    /**
     * updateProductData
     *
     * @param data
     */
    private void updateProductData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductDetailObject productObject = new ItemProductDetailObject();
                productObject.setProductID(object.getString("ProductID"));
                productObject.setProductName(object.getString("ProductName"));
                productObject.setBrandName(object.getString("BrandName"));
                productObject.setCatName(object.getString("CatName"));
                productObject.setIcon(object.getString("Icon"));
                productObjects.add(productObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        recycleAdapter.notifyDataSetChanged();

    }
}
